﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Membership.OpenAuth;
using cs499.Database;

namespace cs499.Account
{
    public partial class Register : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            LinkButton adminMenuButton = (LinkButton)Master.FindControl("LoginView").FindControl("AdminMenuButton");
            adminMenuButton.CssClass = "selected";
        }

        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            //"MainContent_RegisterUser_CreateUserStepContainer"
            
            if (((RadioButton)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("usertypeRadioButtonAdmin")).Checked)
            {
                Roles.AddUserToRole(RegisterUser.UserName, "admin");
            }
            else if (((RadioButton)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("usertypeRadioButtonFaculty")).Checked)
            {
                Roles.AddUserToRole(RegisterUser.UserName, "faculty");
                MembershipUser tempuser = Membership.GetUser(RegisterUser.UserName);
                if (tempuser != null)
                {
                    int depid = Convert.ToInt32(((DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("userDepartmentSelection")).SelectedValue);
                    ListOfDepartment.GetDepartment(ID: depid).CreateFaculty((Guid)tempuser.ProviderUserKey);
                }
                else {
                    throw new ArgumentNullException("Unable to find newly created user", innerException: null);
                }
            }
            
            //FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);

            
            Response.Redirect("~/Admin/ListUsers.aspx?action=User%20Created%20Successfully");
        }

        protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            
            ((CreateUserWizard)sender).LoginCreatedUser = false;
            ((CreateUserWizard)sender).Email = ((CreateUserWizard)sender).UserName;
        }
    }
}